<?php
//得到表名称
function getTable($t = '')
{
    return \Common\Base\TablesBase::getTableName($t);
}

//是否登录
function is_login()
{
    $a = cdSession('member_id');
    return empty($a) ? 0 : (int)$a;
}

//是否登录
function is_admin_login()
{
    $a = session('admin_id');
    return empty($a) ? 0 : (int)$a;
}

//自定义加密函数
function mj_encode($str)
{
    return md5($str.'_sanger');
}

//获取文件夹中的文件列表
function getDirFile($dir, $pre='')
{
    $dir = $_SERVER['DOCUMENT_ROOT'].$dir;
    $fileArray = array();
    if(is_dir($dir)){

        if (false != ($handle = opendir($dir)))
        {
            $i=0;
            while ( false !== ($file = readdir($handle)) )
            {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                if ($file!="." && $file!=".." && strpos($file,"."))
                {
                    $fileArray[$i] = $pre.$file;
                    $i++;
                }
            }
            //关闭句柄
            closedir( $handle );
        }
    }
    return $fileArray;
}

//把xml文件解析成数组
function _xmlToArray($file, $type=false, $returnArray=true)
{
    $file = trim($file);
    if($type){
        if(!is_file($file)){return null;}
        $str = simplexml_load_file($file);
    }else{
        if($file == ''){return null;}
        $str = simplexml_load_string($file);
    }
    return json_decode(json_encode($str), $returnArray);
}

/**
 * 对查询结果集进行排序
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param string $sortby 排序类型 asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby='asc')
{
    if(is_array($list)){
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ( $refer as $key=> $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pk
 * @param string $pid parent标记字段
 * @param string $child 子数组标记
 * @param int $root
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array())
{
    if(is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if(isset($reffer[$child])){
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby='asc');
    }
    return $list;
}

/**
 * 把多维数组转化成一维数组
 *
 * @param array $arr 需要转换的数组，必须有相同的子节点
 * @param string $sub 子节点名称
 * @param array &$rs 返回的引用数组
 *
 * @return array
 */
function floatArray($arr=array(), $sub='_sub', &$rs)
{
    if(empty($arr)){ return false; }
    foreach($arr as $v){
        $tmp2 = $v;
        if(isset($tmp2[$sub])){
            unset($tmp2[$sub]);
            $rs[] = $tmp2;
            floatArray($v[$sub], $sub, $rs);
        }else{
            $rs[] = $v;
        }
    }
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function formatBytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/*调试输出*/
function ddd($var, $exit=false, $printr=false)
{
    if(headers_sent() === false){ header("Content-type:text/html; charset=utf-8"); }
    if($printr){
        echo '<pre>';print_r($var);echo '</pre>';
    }else{
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if(!extension_loaded('xdebug')){
            $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
            $output = '<pre>'. htmlspecialchars($output, ENT_QUOTES).'</pre>';
        }
        echo $output;
    }
    if ($exit){exit;}
    else{return;}
}

//_mkDir
function _mkDir($dir, $mode=0777)
{
    if (!is_dir($dir)) {
        _mkDir(dirname($dir), $mode);
        $old = umask(0);
        @mkdir($dir, $mode);
        umask($old);
        return true;
    }
    return true;
}

//_delDir
function _rmDir($dir)
{
    if( ! is_dir($dir)){ return false; }
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if($file!="." && $file!=".."){
            $fullpath = $dir."/".$file;
            if(!is_dir($fullpath)){unlink($fullpath);}
            else{_rmDir($fullpath);}
        }
    }
    closedir($dh);
    if(_rmDir($dir)){return true;}
    else{return false;}
}

/*
 * 删除指定目录中的所有目录
 * 可扩展增加一些选项（如是否删除原目录等）
 * 删除文件敏感操作谨慎使用
 * @param $dir 目录路径
 * @param array $file_type指定文件类型
 */
function delFile($dir,$file_type='')
{
    if( ! is_dir($dir)){ return false; }
    $files = scandir($dir);
    foreach($files as $filename){
        if($filename!='.' && $filename!='..'){
            $fullpath = $dir."/".$filename;
            if(!is_dir($fullpath)){
                if(empty($file_type)){
                    unlink($fullpath);
                }else{
                    if(is_array($file_type)){
                        //正则匹配指定文件
                        if(preg_match($file_type[0],$filename)){unlink($fullpath);}
                    }else{
                        //指定包含某些字符串的文件
                        if(false!=stristr($filename,$file_type)){unlink($fullpath);}
                    }
                }
            }else{
                delFile($fullpath);
                rmdir($fullpath);
            }
        }
    }
}

//判断是否为email
function isEmail($str)
{
    return (filter_var($str, FILTER_VALIDATE_EMAIL) === false) ? false : true;
}

//手机
function isMobile($string){
    return preg_match('/^1[345678]+\d{9}$/', $string);
}

//随机字符
function randStr($len=6, $type=3, $addChars=null){
    $str = '';
    switch($type) {
        case 1:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 2:
            $chars = str_repeat('0123456789',3);
            break;
        case 3:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
            break;
        case 4:
            $chars = 'abcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        default :
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
            break;
    }
    if($len>10){$len = 10;}
    $charLen = strlen($chars) - 1;
    for($i=0; $i<$len; $i++){
        $str .= $chars[mt_rand(0, $charLen)];
    }
    return $str;
}

//过滤输出数据库数据
function Out($data, $filters='stripslashes,htmlspecialchars_decode')
{
    $filters = explode(',', $filters);
    foreach($filters as $filter){
        if(function_exists($filter)) {
            $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data);
        }
    }
    return $data;
}

//过滤输出数据库数据
function In($data, $filters='addslashes')
{
    $filters = explode(',', $filters);
    foreach($filters as $filter){
        if(function_exists($filter)) {
            $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data);
        }
    }
    return $data;
}

//文件后缀名
function fileExt($filename, $scope=10)
{
    return strtolower(trim(substr(strrchr($filename, '.'), 1, $scope)));
}

/**
 * 过滤
 *
 * @param    array
 * @param    string
 *
 * @return   array
 */
function deep_filter($array, $method)
{
    if (empty($array)) {
        return $array;
    }
    if (is_string($array)) {
        return $method($array);
    } else if (is_array($array)){
        foreach ($array as $key => $val) {
            $array[$key] = deep_filter($val, $method);
        }
    }
    return $array;
}

function br2nl($str = '')
{
    if($str == ''){ return $str; }
    $str = preg_replace("/(<br\s?\/?>\s?)+/i", PHP_EOL, $str);
    return $str;
}

/**
 * Ajax方式返回数据到客户端
 * @access protected
 * @param mixed $data 要返回的数据
 * @param String $type AJAX返回数据格式
 * @return void
 */
function ajaxReturn($data,$type='')
{
    if(empty($type)){ $type = 'JSON'; }
    switch (strtoupper($type)){
        case 'JSON' :
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode($data));
        case 'XML'  :
            // 返回xml格式数据
            header('Content-Type:text/xml; charset=utf-8');
            exit(xml_encode($data));
        case 'JSONP':
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            $handler  =   isset($_GET['jsonp_handler']) ? $_GET['jsonp_handler'] : 'jsonp';
            exit($handler.'('.json_encode($data).');');
        case 'EVAL' :
            // 返回可执行的js脚本
            header('Content-Type:text/html; charset=utf-8');
            exit($data);
    }
    exit;
}

/**
 * 获取IP地理位置接口
 *
 * @param string  $ip
 * @param boolean $to_string
 *
 * @return mixed
 */
function ip_geo($ip='', $to_string=false)
{
    $url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
    $ip_info = json_decode(file_get_contents($url), true);
    if($ip_info['code'] !== 0) { return (true === $to_string) ? '' : []; }
    $ip_info = $ip_info['data'];
    if(true === $to_string){
        $tmp = [];
        if($ip_info['country'] != ''){ $tmp[] = $ip_info['country']; }
        if($ip_info['area'] != ''){ $tmp[] = $ip_info['area']; }
        if($ip_info['region'] != ''){ $tmp[] = $ip_info['region']; }
        if($ip_info['city'] != ''){ $tmp[] = $ip_info['city']; }
        if($ip_info['county'] != ''){ $tmp[] = $ip_info['county']; }
        return empty($tmp) ? '' : implode('-', $tmp);
    }else{
        return $ip_info;
    }
}

//加入到邮件队列表
function send_mail($to=null, $subject='', $body='')
{
    $rec = array();
    if(is_array($to)){
        foreach($to as $t){
            $t = trim($t);
            if(isEmail($t)){
                $rec[] = $t;
            }
        }
    }else{
        if(isEmail($to)){
            $rec[] = $to;
        }
    }
    if(empty($rec)){ return '缺少收件人';}
    $subject = trim($subject);
    if($subject == '') { $subject = C('PAGE_TITLE');}
    $body = trim($body);
    if($body == '') { $body = C('PAGE_TITLE');}

    $L = new \Common\Logic\Common\EmailQueueLogic();
    foreach($rec as $eml){
        $L->add(array('email_to'=>$eml, 'email_title'=>$subject, 'email_content'=>$body));
    }

    return true;
}

/**
 * 用常规方式发送邮件
 *
 * @param string $to
 * @param string $subject
 * @param string $body
 * @param string $name
 * @param array  $attachment
 *
 * @return mixed
 */
function send_mail_now($to = null, $subject = '', $body = '', $name = '', $attachment = null)
{
    $from_email = C('EMAIL_SMTP_USERNAME');
    $from_name = C('PAGE_TITLE');
    $reply_email = C('EMAIL_POP_USERNAME');
    $reply_name = '美吉生物';
    require_once('../App/Common/Tool/PHPMailer/phpmailer.class.php');
    $mail = new PHPMailer; //实例化PHPMailer
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP(); // 设定使用SMTP服务
    $mail->SMTPDebug = 0; // 关闭SMTP调试功能
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth = true; // 启用 SMTP 验证功能
    $mail->SMTPSecure = ''; // 使用安全协议
    $mail->Host = C('EMAIL_SMTP_ADDRESS'); // SMTP 服务器
    $mail->Port = C('EMAIL_SMTP_PORT'); // SMTP服务器的端口号
    $mail->Username = C('EMAIL_SMTP_USERNAME'); // SMTP服务器用户名
    $mail->Password = C('EMAIL_SMTP_PASSWORD'); // SMTP服务器密码
    $mail->SetFrom($from_email, $from_name);
    $replyEmail = $reply_email ? $reply_email : $from_email;
    $replyName = $reply_name ? $reply_name : $from_name;
    $rec = array();//接收人s
    if (empty($to)) {
        return '缺少收件人';
        //$rec[] = C('EMAIL_SMTP_USERNAME'); //邮件地址为空时，默认使用后台默认邮件测试地址
    }
    if (is_string($to)) {
        if(isEmail($to)){
            $rec[] = $to;
        }
    }
    if (is_array($to)) {
        foreach($to as $tt){
            if(isEmail($tt)){
                $rec[] = $tt;
            }
        }
    }
    if ($name == '') {
        $name = C('PAGE_TITLE'); //发送者名称为空时，默认使用网站名称
    }
    if ($subject == '') {
        $subject = C('PAGE_TITLE'); //邮件主题为空时，默认使用网站标题
    }
    if ($body == '') {
        $body = C('PAGE_TITLE'); //邮件内容为空时，默认使用网站描述
    }
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body); //解析
    foreach ($rec as $_to) {
        $mail->AddAddress($_to, $name);
    }
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo; //返回错误信息
}

/**
 * 读取excel成二维数组
 *
 * @param string $xls_path 表格路径
 * @param array  $sheets   需要读取哪几个sheet,默认第一个0
 * @param string $type     驱动 (Excel5读取xls   |   Excel2007读取xlsx)
 *
 * @return mixed
 */
function readExcelToArray($xls_path='', $sheets=array(0), $type='Excel5')
{
    $xls_path = trim($xls_path);
    if( ! is_file($xls_path)){ return false; }
    if(empty($sheets)){ return false; }
    //打开表格
    import('IOFactory', COMMON_PATH.'Tool/PHPExcel/PHPExcel/', '.php');
    $reader = \PHPExcel_IOFactory::createReader($type);
    $obj = $reader->load($xls_path);
    foreach($sheets as $s)
    {
        $datas['sheet_'.$s] = $obj->getSheet($s)->toArray();
    }
    return $datas;
}

/**
 * 由二维数组生成xls，并下载
 *
 * @param array  $datas     数据
 * @param string $save_name 保存名称
 * @param string $type      驱动 (Excel5生成xls   |   Excel2007生成xlsx)
 *
 * @return void
 */
function outputExcelFromArray($datas=array(), $save_name='', $type='Excel5')
{
    if(empty($datas)){ return; }
    $save_name = trim($save_name);
    if($save_name == ''){ $save_name = date('Y-m-d_H-i'); }
    //导入PHPExcel
    import('PHPExcel', COMMON_PATH.'Tool/PHPExcel/', '.php');

    // Create new PHPExcel object
    $objPHPExcel = new \PHPExcel();

    // Set document properties
    $objPHPExcel->getProperties()->setCreator("major")
        ->setLastModifiedBy("major")
        ->setTitle("Document")
        ->setSubject("Document")
        ->setDescription("major")
        ->setKeywords("major")
        ->setCategory("major");

    $objPHPExcel->setActiveSheetIndex(0);

    $objPHPExcel->getActiveSheet()->fromArray($datas);

    $objPHPExcel->getActiveSheet()->setTitle($save_name);

    $hz = ($type == 'Excel2007') ? 'xlsx' : 'xls';

    ob_end_clean();
    // Redirect output to a client’s web browser (Excel5)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$save_name.'.'.$hz.'"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, $type);
    $objWriter->save('php://output');
    exit;
}

//得到员工的姓名，头像
function getMemberRealNameAvatar($member_id = 0)
{
    $member_id = intval($member_id);
    if($member_id < 1){ return array(); }
    $m_member = new \Common\Model\Common\MemberModel();
    $info = $m_member->getTableMember(4, array('member_id'=>$member_id), 'real_name,avatar,gender');
    if(empty($info)){ return array(); }
    return $info;
}

/**
 * 上传图像
 */
function upload_img($fieldName, $path=''){
    $upload = new \Think\Upload();// 实例化上传类
    $upload->maxSize  = 3145728 ;// 设置附件上传大小
    $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
    $upload->rootPath = 'uploads/'.$path.'/'; // 设置附件上传根目录
    // 上传单个文件
    $info = $upload->uploadOne($_FILES[$fieldName]);
    $data['success']=true;
    if(!$info) {// 上传错误提示错误信息
        $data['success']=false;
        $data['msg']=$upload->getError();
    }else{// 上传成功 获取上传文件信息
        $data['url']="/".$upload->rootPath.$info['savepath'].$info['savename'];
        $data['msg']="上传成功";
    }
    return $data;
}

function upload_multiple_img($fieldName , $path = '')
{
    $upload = new \Think\Upload();// 实例化上传类
    $upload->maxSize  = 3145728 ;// 设置附件上传大小
    $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
    $upload->rootPath = 'uploads/'.$path.'/'; // 设置附件上传根目录

    $info = $upload->upload($_FILES[$fieldName]);
    
    $data['success']=true;
    if(!$info) {// 上传错误提示错误信息
        $data['success']=false;
        $data['msg']=$upload->getError();
    }else{// 上传成功 获取上传文件信息
        $data['url']="/".$upload->rootPath.$info['savepath'].$info['savename'];
        $data['msg']="上传成功";
    }
    return $data;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}


/**
 * 按照key组合数组
 *
 * @param    array
 * @param    string
 *
 * @return   array
 **/
function arrayGroup($array, $key)
{
	if (empty($array)) {
		return array();
	}

	$array1 = array();

	foreach ($array as $val) {
		$array1[$val[$key]][] = $val;
	}

	return $array1;
}


/**
 * 获取指定的键值
 * 
 * @param    array
 * @param    string
 *
 * @return   array
 */
function getSingleKey($array, $key)
{
    $infos = array();
    if(empty($array)){ return $infos; }
    foreach ($array as $val) {
        isset($val[$key]) && $infos[] = $val[$key];
    }

    return $infos;
}


/**
 * 按照key组合数组
 *
 * @param    array
 * @param    string
 *
 * @return   array
 **/
function singleGroup($array, $key)
{
	if (empty($array)) {
		return array();
	}

	$array1 = array();

	foreach ($array as $val) {
		$array1[$val[$key]] = $val;
	}

	return $array1;
}

function IEVersion()
{
    $version = 0;
    preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
    if(count($matches)<2){
        preg_match('/Trident\/\d{1,2}.\d{1,2}; rv:([0-9]*)/', $_SERVER['HTTP_USER_AGENT'], $matches);
    }
    if(count($matches)>1){
        $version = (int)$matches[1];
    }
    return $version;
}

/**
 * 得到，某年的"月份&星期"的起止时间戳
 *
 * @param int     $year
 * @param int     $offset
 * @param boolean $use_cache
 *
 * @return array
 */
function monthWeekTimeStamp($year=0, $offset=1, $use_cache=true)
{
    $year = intval($year); if($year < 1971){ $year = (int)date('Y', time()); }

    //查看缓存是否存在
    if($use_cache)
    {
        $cache = F('monthWeekTimeStamp_'.$year);
        if( ! empty($cache)){ return $cache; }
    }

    $offset = intval($offset); if($offset < 0){ $offset = 1; }
    $ts = mktime(0, 0, 0, 1, 1, $year);
    $base_month = 1;
    $base_week = 1;

    $fw = (int)date('N', $ts);//指定的时间戳是星期几
    $one_week_ts = 7*86400;//一周多少秒
    if($fw !== 1){
        $WWW = (int)date('W', $ts);//指定的时间戳是第几周
        if($WWW !== 1){//则是上年的最后一周
            $week_begin_ts = $ts + (8 - $fw)*86400;
        }else{
            $week_begin_ts = $ts - ($fw - 1)*86400;
        }
    }else{
        $week_begin_ts = $ts;
    }

    $rt = array();
    $i = 1;

    //月份
    for($ix=1; $ix<=12; $ix++)
    {
        $month_begin_ts = strtotime($year.'-'.$ix.'-1');
        if($ix === 12){
            $month_end_ts = strtotime(($year+1).'-1-1') - $offset;
        }else{
            $month_end_ts = strtotime($year.'-'.($ix+1).'-1') - $offset;
        }
        $rt['month'][$ix] = array(
            'month'=>$ix,
            'month_begin'=>$month_begin_ts,
            'month_end'=>($month_end_ts - $offset),
            'month_day_ct'=>round((($month_end_ts - $month_begin_ts)/86400)),
            'b'=>date('Y-m-d', $month_begin_ts),
            'e'=>date('Y-m-d', ($month_end_ts - $offset)),
        );
    }

    //星期
    while(true)
    {
        $next_week_begin_ts = $week_begin_ts + $one_week_ts;

        $_y = (int)date('Y', $next_week_begin_ts);
        if($_y > $year){
            $_W = (int)date('W', $next_week_begin_ts);
            if($_W > 1){//虽然到下一年了，但还是属于当年的最后一周
                break;
            }
        }

        $_m = (int)date('n', $week_begin_ts);
        $_y = (int)date('Y', $week_begin_ts);
        if($_y===$year && $_m>$base_month){
            $base_month++;
        }

        $rt['week'][$i] = array(
            'month'=>$base_month,
            'week_ct'=>$base_week,
            'week_begin'=>$week_begin_ts,
            'week_end'=>($next_week_begin_ts - $offset),
            'b'=>date('Y-m-d', $week_begin_ts),
            'e'=>date('Y-m-d', ($next_week_begin_ts - $offset)),
        );

        $i++;

        $base_week++;

        $week_begin_ts = $next_week_begin_ts;
    }

    //缓存结果
    if($use_cache)
    {
        F('monthWeekTimeStamp_'.$year, $rt);
    }

    return $rt;
}

/**
 * 得到指定天数的起始时间戳
 *
 * @param int $year
 * @param int $day (1-365)
 *
 * @return array
 */
function getDayStamp($year=0, $day=0)
{
    $year = intval($year); if($year < 1971){ $year = (int)date('Y', time()); }
    $day = intval($day); if($day<0 || $day>(int)date('z', strtotime($year.'-12-31'))){ $day = (int)date('z', time()); }
    $rt['begin_ts'] = strtotime($year.'-01-01')+(86400*$day);
    $rt['end_ts'] = $rt['begin_ts'] + 86399;
    return $rt;
}

/**
 * 数字转换为中文价格
 * 
 * @param int
 * 
 * @return string
 */
function cny($ns) { 
    static $cnums=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"), 
        $cnyunits=array("圆","角","分"), 
        $grees=array("拾","佰","仟","万","拾","佰","仟","亿"); 
    list($ns1,$ns2)=explode(".",$ns,2); 
    $ns2=array_filter(array($ns2[1],$ns2[0])); 
    $ret=array_merge($ns2,array(implode("",  _cny_map_unit(str_split($ns1),$grees)),"")); 
    $ret=implode("",array_reverse(_cny_map_unit($ret,$cnyunits))); 
    return str_replace(array_keys($cnums),$cnums,$ret); 
}

function _cny_map_unit($list,$units) { 
    $ul=count($units); 
    $xs=array(); 
    foreach (array_reverse($list) as $x) { 
        $l=count($xs); 
        if ($x!="0" || !($l%4)) $n=($x=='0'?'':$x).($units[($l-1)%$ul]); 
        else $n=is_numeric($xs[0][0])?$x:''; 
        array_unshift($xs,$n); 
    } 
    return $xs; 
}

/**
 * 由字符串拆分得到对应整型数组
 *
 * @param string $string = 1,2,3,66,
 * @param string $delimit
 * @param string $type [negative,all,positive]
 *
 * @return array(1,2,3,66)
 */
function getIntArrayFromString($string='', $delimit=',', $type='positive')
{
    $fst = getArrayFromString($string, $delimit);
    if(empty($fst)){ return array(); }
    if( ! in_array($type, array('negative', 'positive', 'all'))){ $type = 'positive'; }
    $rs = array();
    foreach($fst as $t){
        $t = intval($t);
        if($type=='positive' && $t>0){
            $rs[] = $t;
        }elseif($type=='negative' && $t<0){
            $rs[] = $t;
        }else{
            $rs[] = $t;
        }
    }
    return $rs;
}

/**
 * 由字符串拆分得到对应数组
 *
 * @param string $string = 1,2,3,66,
 * @param string $delimit
 *
 * @return array(1,2,3,66)
 */
function getArrayFromString($string='', $delimit=',')
{
    $string = trim($string); if($string == ''){ return array(); }
    $delimit = trim($delimit); if($delimit == ''){ return array(); }
    $tmp = explode($delimit, $string);
    $rs = array();
    foreach($tmp as $t){
        $t = trim($t);
        if($t != ''){
            $rs[] = $t;
        }
    }
    return $rs;
}

//得到干净字符串，转载自snoopy
function cleanText($document = '')
{
    $document = trim($document);
    if($document == ''){ return $document; }

    $search = array("'<script[^>]*?>.*?</script>'si", // strip out javascript
        "'<[\/\!]*?[^<>]*?>'si", // strip out html tags
        "'([\r\n])[\s]+'", // strip out white space
        "'&(quot|#34|#034|#x22);'i", // replace html entities
        "'&(amp|#38|#038|#x26);'i", // added hexadecimal values
        "'&(lt|#60|#060|#x3c);'i",
        "'&(gt|#62|#062|#x3e);'i",
        "'&(nbsp|#160|#xa0);'i",
        "'&(iexcl|#161);'i",
        "'&(cent|#162);'i",
        "'&(pound|#163);'i",
        "'&(copy|#169);'i",
        "'&(reg|#174);'i",
        "'&(deg|#176);'i",
        "'&(#39|#039|#x27);'",
        "'&(euro|#8364);'i", // europe
        "'&a(uml|UML);'", // german
        "'&o(uml|UML);'",
        "'&u(uml|UML);'",
        "'&A(uml|UML);'",
        "'&O(uml|UML);'",
        "'&U(uml|UML);'",
        "'&szlig;'i",
    );
    $replace = array("",
        "",
        "\\1",
        "\"",
        "&",
        "<",
        ">",
        " ",
        chr(161),
        chr(162),
        chr(163),
        chr(169),
        chr(174),
        chr(176),
        chr(39),
        chr(128),
        "ä",
        "ö",
        "ü",
        "Ä",
        "Ö",
        "Ü",
        "ß",
    );

    $text = preg_replace($search, $replace, $document);

    return $text;
}

//组装返回信息
function genReturn($sign='y', $note='ok', $extra=array())
{
    $rt = array();
    $rt['st'] = $sign;
    $rt['note'] = $note;
    if( ! empty($extra)){
        foreach($extra as $k=>$v){
            $rt[$k] = $v;
        }
    }
    return $rt;
}

//kindEditor配套函数，不能删除
function kindEditorCmpFunc($a, $b)
{
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
        return -1;
    }
    else if (!$a['is_dir'] && $b['is_dir']) {
        return 1;
    }
    else {
        if ($order == 'size') {
            if ($a['filesize'] > $b['filesize']) {
                return 1;
            }
            else if ($a['filesize'] < $b['filesize']) {
                return -1;
            }
            else {
                return 0;
            }
        }
        else if ($order == 'type') {
            return strcmp($a['filetype'], $b['filetype']);
        }
        else {
            return strcmp($a['filename'], $b['filename']);
        }
    }
}

//代替原生的 basename 函数
function get_basename($filename)
{
    return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}